package code.juc.stopThread.volatiledemo;

/**
 * 使用Volatile标志位的方法, 停止线程的局限性; part1：看似可行.
 */
public class WrongWayVolatileStopThread implements Runnable {

    private volatile boolean canceled = false;

    @Override
    public void run() {
        int num = 0;
        try {
            while (num < Integer.MAX_VALUE / 2 && !canceled) {
                if (num % 100 == 0) {
                    System.out.println(num + " is mod 100!");
                }

                num++;
                Thread.sleep(10);
            }
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        WrongWayVolatileStopThread runnable = new WrongWayVolatileStopThread();
        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(5000);

        System.out.println("Modify canceled is true!");
        runnable.canceled = true;
    }
}
